package com.heima.wemedia.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dtos.PageResponseResult;
import com.heima.common.dtos.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.file.service.FileStorageService;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.utils.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
@Transactional
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Resource
    private FileStorageService fileStorageService;

    /**
     * 图片上传
     */
    @Override
    public ResponseResult<WmMaterial> uploadPicture(MultipartFile multipartFile) {
        //1.检查参数
        if (multipartFile == null || multipartFile.getSize() == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.上传图片到minIO中
        String originalFilename = multipartFile.getOriginalFilename();   //aa.jpg
        String postfix = StrUtil.subAfter(originalFilename, '.', true); //文件后缀
        String fileName = StrUtil.format("{}.{}", IdUtil.simpleUUID(), postfix);
        String fileId;
        try {
            fileId = fileStorageService.uploadImgFile("", fileName, multipartFile.getInputStream());
            log.info("上传图片到MinIO中，fileId:{}", fileId);
        } catch (IOException e) {
            log.error("WmMaterialServiceImpl-上传文件失败");
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR, "上传文件失败");
        }

        //3.保存到数据库中
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setUserId(WmThreadLocalUtil.getUser().getId());
        wmMaterial.setUrl(fileId);
        wmMaterial.setIsCollection((short) 0);
        wmMaterial.setType((short) 0);
        wmMaterial.setCreatedTime(new Date());
        save(wmMaterial);

        //4.返回结果
        return ResponseResult.okResult(wmMaterial);
    }

    @Override
    public PageResponseResult<List<WmMaterial>> findList(WmMaterialDto dto) {
        //1.检查参数
        dto.checkParam();
        //2.分页查询
        Page<WmMaterial> page = new Page<>(dto.getPage(),dto.getSize());
        LambdaQueryWrapper<WmMaterial> wrapper = Wrappers.lambdaQuery();
        //3.是否收藏
        wrapper.eq(ObjectUtil.equal(dto.getIsCollection(),1),WmMaterial::getIsCollection,dto.getIsCollection());
        //4.按照用户查询
        wrapper.eq(WmMaterial::getUserId,WmThreadLocalUtil.getUser().getId());
        //5.按照时间倒序
        wrapper.orderByDesc(WmMaterial::getCreatedTime);
        //6.查询顺序
        super.page(page,wrapper);
        //7.结果返回
        return  PageResponseResult.<List<WmMaterial>>builder()
                .currentPage(dto.getPage())
                .size(dto.getSize())
                .total(Convert.toInt(page.getTotal()))
                .data(page.getRecords())
                .build();
    }

    @Override
    public ResponseResult<Void> delect(Integer id) {
        //id 空
        if(ObjectUtil.isEmpty(id)){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //id 空集合空字符串
        if (ObjectUtil.isEmpty(this.getById(id))) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "数据不存在.");
        }
        //删除成不成功
        if (this.removeById(id)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.SUCCESS);
        } else {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

    }

    @Override
    public ResponseResult<Void> cancelCollect(Integer id) {
        return isCancelCollect(id,0);
    }

    @Override
    public ResponseResult<Void> collect(Integer id) {
        return isCancelCollect(id,1);
    }




    //判断是否取消还是收藏
    public ResponseResult<Void> isCancelCollect(Integer wmId, Integer id) {
        WmMaterial wmMaterial = this.getById(wmId);
        if (wmMaterial == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        } else {
            if(id == 0){
                wmMaterial.setIsCollection((short) 0);
            }else {
                wmMaterial.setIsCollection((short) 1);
            }
            boolean isSuccess = this.updateById(wmMaterial);
            if (isSuccess) {
                return ResponseResult.errorResult(AppHttpCodeEnum.SUCCESS);
            } else {
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
            }
        }

    }

}
